 var netWork = require('../../../utils/netWork.js');
 var api = require('../../../utils/api.js');

 const log = require('../../../utils/logs.js');

 var isClick = true;
 Page({

   /**
    * 页面的初始数据
    */
   data: {
     imagesUrl: getApp().globalData.imagesUrl,
     topHeight: 0,
     ani: 0, //动画是否执行
     readRule: false,
     readPrivate: false,
     date: '',
     showNewuser: -1,
     showAlert: false,
     activityInfo: {},
     change_activityInfo: {},
     changeFeast: false,
     isShowModalPriv:false,
   },

   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
     try {
       const {
         SDKVersion = ''
       } = wx.getSystemInfoSync();
       // 获取系统信息
       const that = this;
       wx.getSystemInfo({
         success: function (res) {
           that.setData({
             addHeight: (res.screenHeight * res.pixelRatio - 1334) / 6
           });
         }
       });
       console.log(that.data.addHeight)
       log.info(SDKVersion)
       const compatibility = util.compareVersion(SDKVersion, '2.2.2');
       log.info(compatibility)
       if (compatibility == -1) {
         wx.showModal({
           content: '您的微信版本过低，请升级后再来吧~',
           confirmText: '我知道了',
           showCancel: false
         });
         return;
       }
     } catch (e) {}
     try {
       // 检测是否可以调用getUpdateManager检查更新
       if (!wx.canIUse("getUpdateManager")) return;
       let updateManager = wx.getUpdateManager();
       // 获取全局唯一的版本更新管理器，用于管理小程序更新
       updateManager.onCheckForUpdate(function (res) {
         log.info(res)
         // 监听向微信后台请求检查更新结果事件
         log.info("是否有新版本：" + res.hasUpdate);
         if (res.hasUpdate) {
           //如果有新版本
           // 小程序有新版本，会主动触发下载操作
           updateManager.onUpdateReady(function () {
             //当新版本下载完成，会进行回调
             wx.showModal({
               title: '更新提示',
               content: '新版本已经准备好，单击确定重启小程序',
               showCancel: false,
               success: function (res) {
                 if (res.confirm) {
                   // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                   updateManager.applyUpdate();
                 }
               }
             })
           })
           // 小程序有新版本，会主动触发下载操作（无需开发者触发）
           updateManager.onUpdateFailed(function () {
             //当新版本下载失败，会进行回调
             wx.showModal({
               title: '提示',
               content: '检查到有新版本，但下载失败，请稍后尝试',
               showCancel: false,
             })
           })
         }
       });
     } catch (e) {
       e
     }
     //高度处理
     let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');

     this.setData({
       topHeight: topHeight,
       icon: 'common/loading',
       showNewuser: JSON.parse(options.isBanquetMaster)==true ? 1 : 0
     });
     console.log('this.data.showNewuser')
     console.log(this.data.showNewuser)
     api.judgeNetworkStatus(function (res) {
       if ("none" == res) return;
     })
     var myDate = new Date();
     var time = myDate.toLocaleDateString().split('/').join('-');
     this.setData({
       date: time
     });
     if (options.activityInfo) {
       this.setData({
         activityInfo: JSON.parse(options.activityInfo),
         change_activityInfo: JSON.parse(options.activityInfo),
       })
     } else { //请求后台，查询宴席活动明细
       this.queryFeastActInfo();
     }

   },
   //表单提交按钮,校验
   formSubmit: function (e) {
     //防止重复点击或者点击过快
     console.log("点击了");
     if (!isClick) {
       console.log("重复返回~");
       return;
     }
     if (isClick) {
       isClick = false;
       //定时器
       setTimeout(function () {
         isClick = true;
       }, 3000); //3秒内不能重复点击
     }
     let masterName = e.detail.value.masterName;
     let masterPhone = e.detail.value.masterPhone;
     let hotelName = e.detail.value.hotelName;
     let addressInfo = e.detail.value.addressInfo;
     let planCount = e.detail.value.planCount;
     if (masterName.trim() == "") {
       wx.showToast({
         title: '请输入席主姓名',
         icon: 'none'
       })
       return;
     }
     if (masterPhone.trim() == "") {
       wx.showToast({
         title: '请输入手机号码',
         icon: 'none'
       })
       return;
     }

     let a = /^1\d{10}$/;
     if (!a.test(masterPhone)) {
       wx.showToast({
         title: '请输入正确的手机号码',
         icon: 'none'
       })
       return;
     }

     if (planCount.trim() == "") {
       wx.showToast({
         title: '请输入用酒数量',
         icon: 'none'
       })
       return;
     }
     if(planCount.trim()<=0){
      wx.showToast({
        title: '用酒数量不能小于1瓶',
        icon: 'none'
      })
      return;
     }
     if(planCount.trim()>100000){
      wx.showToast({
        title: '用酒数量不能超过10万瓶',
        icon: 'none'
      })
      return;
     }
     if (addressInfo.trim() == "") {
       wx.showToast({
         title: '请输入宴席位置',
         icon: 'none'
       })
       return;
     }
     if (hotelName.trim() == "") {
       wx.showToast({
         title: '请输入宴席场地',
         icon: 'none'
       })
       return;
     }


     let newData = this.data.change_activityInfo;
     newData['masterName'] = masterName;
     newData['masterPhone'] = masterPhone;

     newData['hotelName'] = hotelName;
     newData['planCount'] = planCount;
     newData['addressInfo'] = addressInfo;

     //保存信息
     const that = this;
     wx.showModal({
       title: '提示',
       content: '确认保存吗？',
       success: function (sm) {
         if (sm.confirm) {

           netWork.POST_Json('banquet/update', {
             data: {
               activityBanquetId: newData.activityBanquetId,
               masterPhone: newData.masterPhone,
               masterName: newData.masterName,
               startTime: that.data.startTime + ' 00:00:00',
               addressInfo: newData.addressInfo,
               hotelName: newData.hotelName,
               planCount: newData.planCount,
             },
             success: function (res) {
               if (res.data.retCode == undefined) {
                 //错误提示
                 that.setData({
                   showAlert: true,
                   alertContent: '操作失败,请稍后重试'
                 })
               }
               if (res.data.retCode == '0000') {
                 that.setData({
                   activityInfo: newData,
                   change_activityInfo: newData
                 });
                 wx.showToast({
                   title: '保存成功',
                   icon: 'success'
                 })
                 that.setData({
                   changeFeast: false
                 });
                 that.queryFeastActInfo();

               } else {
                 //错误提示
                 that.setData({
                   showAlert: true,
                   alertContent: res.data.retMsg+'[' + res.data.retCode + ']'
                 })
               }
             },
             fail: function (res) {
               //错误提示
               that.setData({
                 showAlert: true,
                 alertContent: '操作失败,请稍后重试'
               })
             }
           });
         } else if (sm.cancel) {

         }
       }
     })



   },
   isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })

  },
   queryFeastActInfo() {
     const that = this;
     that.isLoading(true, '加载中...')
     netWork.POST_Json('banquet/info', {
       data: {
         qrcodeAPublish: wx.getStorageSync('qrCodeFeast'),
       },
       success: function (res) {
         that.isLoading(false, '加载中...')
         if (res.data.retCode == undefined) {
           wx.showToast({
             title: '操作失败，稍后重试',
             icon: 'none'
           })
         }
         if (res.data.retCode == '0000') {
           that.setData({
             activityInfo: res.data.data,
             change_activityInfo: res.data.data
           })

         } else {
           wx.showToast({
             title: '操作失败，稍后重试',
             icon: 'none'
           })
         }
       },
       fail: function (res) {
         that.isLoading(false, '加载中...')
         wx.showToast({
           title: '操作失败，稍后重试',
           icon: 'none'
         })
       }
     });
   },
   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function () {

   },
   canlAuth() {
     this.setData({
       showNewuser: -1
     })
   },
   onClickPrivate: function () {
     let readPrivate = this.data.readPrivate;
     if (readPrivate) {
       this.setData({
         readPrivate: false
       })
     } else {
       this.setData({
         readPrivate: true
       })
     }

   },

   /**
    * 勾选、取消活动规则
    */
   onClickRule: function () {
     let readRule = this.data.readRule;
     if (readRule) {
       this.setData({
         readRule: false
       })
     } else {
       this.setData({
         readRule: true
       })
     }

   },
   sureAuth() {
     if (!this.data.readRule) {
       wx.showToast({
         title: '请您阅读并勾选活动规则',
         icon: 'none'
       })
       return;
     }
     if (!this.data.readPrivate) {
       wx.showToast({
         title: '请您阅读并勾选隐私政策',
         icon: 'none'
       })
       return;
     }
     this.setData({
       showNewuser: 0
     })
   },
   changeAct() {
     if (this.data.showNewuser == -1 || this.data.showNewuser == 1) {
       this.setData({
         showNewuser: 1
       })
       return;
     }
     this.setData({
       changeFeast: true,
       startTime: this.data.change_activityInfo.startTime
     });
   },
   canSaveFeastAct() {
     this.setData({
       changeFeast: false
     });
   },

   sureAct() {
     if (this.data.showNewuser == -1 || this.data.showNewuser == 1) {
       this.setData({
         showNewuser: 1
       })
       return;
     }
     wx.requestSubscribeMessage({
      tmplIds: ['agnOCFc4zZ80zde2HkOppI9QoqNlysud_LoMzr0dnKw'],
      success(res) {
        var subscriptionData = [];
        for (let key in res) {
          if (key !== "errMsg" && key !== "errorCode") {
            let obj = {
              template_id: key,
              status: res[key]
            };
          }
           
        }


      },
      fail(res) {
        console.log(res);
         
      }
    })
     //确认信息
     const that = this;
     that.isLoading(true, '加载中...')
     netWork.POST_Json('banquet/confirm', {
       data: {
         activityBanquetId: that.data.activityInfo.activityBanquetId
       },
       success: function (res) {
         that.isLoading(false, '加载中...')
         if (res.data.retCode == undefined) {
           wx.showToast({
             title: '操作失败，稍后重试',
             icon: 'none'
           })
         }
         if (res.data.retCode == '0000') {
           wx.redirectTo({
             url: '../activated/activated',
           })

         } else {
           wx.showToast({
             title: '操作失败，稍后重试',
             icon: 'none'
           })
         }
       },
       fail: function (res) {
         that.isLoading(false, '加载中...')
         wx.showToast({
           title: '操作失败，稍后重试',
           icon: 'none'
         })
       }
     });
   },
   bindDateChange: function (e) {
     console.log('picker发送选择改变，携带值为', e.detail.value);

     this.setData({
       startTime: e.detail.value
     })
   },
   ok() {
    this.setData({
      barcode: '',
      alertContent: '',
      showAlert: false
    })
  },
   feastRule() {
     let activityBanquetId = this.data.activityInfo.activityBanquetId;
     wx.navigateTo({
       url: '../feastRule/feastRule?activityBanquetId=' + activityBanquetId,
     })
   },
   showPri(){
     this.setData({isShowModalPriv:true})
   },
   clickClose(){
    this.setData({isShowModalPriv:false})
   }
 })